package com.zhiqiang.gameserver.netty;

import com.zhiqiang.gameserver.constant.R;
import com.zhiqiang.gameserver.entity.ZQGameServerEntity;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;

import java.nio.ByteOrder;
/**
 * @author YAO
 */
public class NettyGameServerDecoder extends LengthFieldBasedFrameDecoder {

    /**
     * @param byteOrder
     * @param maxFrameLength
     *            字节最大长度,大于此长度则抛出异常
     * @param lengthFieldOffset
     *            开始计算长度位置,这里使用0代表放置到最开始
     * @param lengthFieldLength
     *            描述长度所用字节数
     * @param lengthAdjustment
     *            长度补偿,这里由于命令码使用2个字节.需要将原来长度计算加2
     * @param initialBytesToStrip
     *            开始计算长度需要跳过的字节数
     * @param failFast
     */
    public NettyGameServerDecoder(ByteOrder byteOrder, int maxFrameLength, int lengthFieldOffset, int lengthFieldLength, int lengthAdjustment, int initialBytesToStrip, boolean failFast) {
        super(byteOrder, maxFrameLength, lengthFieldOffset, lengthFieldLength, lengthAdjustment, initialBytesToStrip, failFast);
    }

    public NettyGameServerDecoder() {
        this(ByteOrder.BIG_ENDIAN,
                R.EncoderAndDecoder.MAX_FRAME_LENGTH,
                R.EncoderAndDecoder.LENGTH_FIELD_OFFSET,
                R.EncoderAndDecoder.LENGTH_FIELD_LENGTH,
                R.EncoderAndDecoder.LENGTH_ADJUSTMENT,
                R.EncoderAndDecoder.INITIAL_BYTES_TO_STRIP,
                true);
    }

    /**
     * 根据构造方法自动处理粘包,半包.然后调用此decode
     * */
    @Override
    protected Object decode(ChannelHandlerContext ctx, ByteBuf byteBuf) throws Exception {

        ByteBuf frame = (ByteBuf) super.decode(ctx, byteBuf);
        if (frame == null) {
            return null;
        }
        ZQGameServerEntity msg = new ZQGameServerEntity();
        msg.setLen(frame.readInt());
        msg.setMsgType(frame.readInt());
        msg.setUid(frame.readInt());
        msg.setSeq(frame.readInt());
        msg.setResult(frame.readInt());
        msg.setV6(frame.readInt());
        msg.setV7(frame.readInt());
        msg.setV8(frame.readInt());
        msg.setV9(frame.readInt());
        msg.setV10(frame.readInt());
        msg.setV11(frame.readInt());
        msg.setV12(frame.readInt());
        // 其它数据为实际数据
        byte[] data = new byte[frame.readableBytes()];
        frame.readBytes(data);
        msg.setData(data);
        return msg;
    }
}
